﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wholesaler.Models.DBModels;
using Yunzuan.Common.Log;
using Yunzuan.Foundation.DataAccess;
using YunZuan.Models.Entities;
using Yunzuan.Foundation.Serializer;
using Yunzuan.Foundation.Web;
using Yunzuan.Foundation.Web_api;
using YunZuan.Models;

namespace Yunzuan.Common
{
    public class ComLendOrder
    {
        public static Type type = typeof(ComLendOrder);
        static string msgInfo = "{{\"msgcode\":{0},\"msginfo\":\"{1}\"}}";
        /// <summary>
        /// 添加借货单
        /// </summary>
        /// <param name="goodType">商品类别ID</param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string AddLendOrder(int goodType, string param)
        {
            string typeName = GoodsType.GetTypeName(goodType);
            CommonConst.logParam = param;
            HashParam HsParam = Json.Deserialize<HashParam>(param);
            string tttagKey = CommonUrl.getURL(HsParam, param, typeName + "开始创建借货单");

            
            List<LendOrder> list = new List<LendOrder>();
            LendOrder lendorder;
            CustomerInfo customer = YZ.GetDatabase(tttagKey).Get<CustomerInfo>(HsParam.GetInt("CustomerID"));//CustomerID必传
            UserInfo userinfo = YZ.GetDatabase(tttagKey).QueryForObject<UserInfo>("User.getPurchaseAgentByUserId", customer.SalesUserID);
            string lendOrderNo ="L"+ DateTime.Now.ToString("MMddHHmmssfff");
            if (customer != null)
            {
                string[] InventoryIDs = { };
                if (HsParam.ContainsKey("IDs"))
                    InventoryIDs = HsParam.GetString("IDs").TrimEnd(',').Split(',');
                else if (HsParam.ContainsKey("InventoryIDs"))
                    InventoryIDs = HsParam.GetString("InventoryIDs").TrimEnd(',').Split(',');
                int addCount = 0;
                StringBuilder sbStrIds = new StringBuilder();
                for (int i = 0; i < InventoryIDs.Length; i++)
                {
                    Hashtable hash = new Hashtable();
                    hash.Add("CustomerID", customer.CustomerID);
                    hash.Add("GoodsTypeID", goodType);
                    hash.Add("GoodsID", InventoryIDs[i]);
                    lendorder = YZ.GetDatabase(tttagKey).QueryForObject<LendOrder>("LendOrder.GetLendOrder", hash);
                    if (lendorder == null)
                    {
                        lendorder = new LendOrder();
                        lendorder.CustomerID = customer.CustomerID;//客户ID
                        lendorder.LendOrderNo = lendOrderNo;
                        lendorder.UserID = customer.SalesUserID.Value; //业务ID
                        lendorder.GoodsID = Convert.ToInt32(InventoryIDs[i]);
                        lendorder.IsReturn = HsParam.ContainsKey("IsReturn") ? HsParam.GetInt("IsReturn").Value : 0;
                        lendorder.IsReturnValues = HsParam.ContainsKey("IsReturnValues") ? HsParam.GetDecimal("IsReturnValues").Value : 0;
                        lendorder.GoodsTypeID = goodType;
                        lendorder.CreateTime = DateTime.Now;//加入购物车时间
                        lendorder.Remarks = HsParam.ContainsKey("Remarks") ? HsParam.GetString("Remarks") : "";
                        lendorder.InventoryCount = HsParam.ContainsKey("InventoryCount") ? HsParam.GetDecimal("InventoryCount"):1;
                        list.Add(lendorder);
                        sbStrIds.Append(lendorder.GoodsID + ",");
                    }
                    else
                    {
                        addCount++;
                    }
                }
                using (ITransaction tran_addRingCart = YZ.GetTransaction(tttagKey))
                {
                    try
                    {
                        if (list.Count == 0)
                            return string.Format(CommonConst._msgInfo, "true", "创建借货单成功", list.Count, addCount);
                        else
                        {
                            tran_addRingCart.Insert("LendOrder.AddLendOrderList", list);
                            tran_addRingCart.CommitTransaction(); //提交  
                            Msg msgS = new Msg();
                            msgS.TagKey = tttagKey;
                            msgS.Desc = "创建借货单成功" + JsonConvert.SerializeObject(param);
                            ConmonMQMsgClass.send(msgS);

                            #region 更新商品状态为借出
                            TransmissionOrderResult tor = new TransmissionOrderResult();
                            int totalSeconds;
                            string signStr;
                            string batchUpdateDiaParam = "{\"Status\":\"2\",\"filter\":{\"ID\":[";
                            for (int i = 0; i < list.Count; i++)
                            {
                                if (i == 0)
                                    batchUpdateDiaParam += "\"" + list[i].GoodsID + "\"";
                                if (i > 0)
                                    batchUpdateDiaParam += ",\"" + list[i].GoodsID + "\"";
                            }
                            batchUpdateDiaParam += "]}}";
                            var guid = Guid.NewGuid().ToString();
                            var objParams = JsonConvert.DeserializeObject<JObject>(batchUpdateDiaParam);//ID数组使用DeserializeObject.ID单个见加入购物车方法

                            var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                            MyHttpRequest.SignByParams(guid, lastStr.ToString(), tttagKey, out totalSeconds, out signStr);
                            //获取数据仓库库存（远程） 多个ID获取多条库存
                            var result =
                                 MyHttpRequest.PostJSONByRequestParam(
                                    new RequestInfo() { RequestJson = batchUpdateDiaParam, RequestUrl = GlobalConfig.TransmissionBatchUpStockURL }
                                     , 3, guid, signStr, totalSeconds, null, Yunzuan.Foundation.Web_api.MyHttpRequest.RequestLib.PUT
                            );
                            if (result.Contains(".py"))
                            {
                                result = string.Format(msgInfo, "false", "数据远程服务错误");
                            }
                            msgS = new Msg();
                            msgS.TagKey = tttagKey;
                            msgS.Desc = "批量修改裸钻借出状态：数据中心返回结果" + result;
                            ConmonMQMsgClass.send(msgS);
                            #endregion
                            #region 提交成功后发送短信给业务
                            if (!HsParam.ContainsKey("IsReturn") && userinfo != null && userinfo.Mobile!=null && customer != null)
                                SendMsg(userinfo.Mobile, userinfo.UserName, customer.NickName);  
                            #endregion
                            return string.Format(CommonConst._msgInfo, "true", "创建借货单成功", list.Count, addCount);
                        }
                    }
                    catch (Exception ex)
                    {
                        CommonLog.GetMethodInfoAndWriteLogs(type, ex);
                        tran_addRingCart.RollBackTransaction();
                        Msg msgS = new Msg();
                        msgS.TagKey = tttagKey;
                        msgS.Desc = "异常信息：创建借货单失败" + ex.StackTrace + "参数：" + CommonConst.logParam;
                        ConmonMQMsgClass.send(msgS);
                        return string.Format(CommonConst._msgInfo, "false", "创建借货单失败", 0, 0);
                    }
                }

            }
            else
            {
                return string.Format(CommonConst._msgInfo, "false", "客户不存在", 0, 0);
            }  
        }

        /// <summary>
        /// 删除借货单
        /// </summary>
        /// <param name="goodType">商品类别ID</param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string DelLendOrderByIds(int goodType, string param)
        {
            CommonConst.logParam = param;
            HashParam str = JsonConvert.DeserializeObject<HashParam>(param);
            string tttagKey = CommonUrl.getURL(str,param, "删除借货单"); 


            Hashtable hash = new Hashtable();
            hash.Add("GoodsTypeID", goodType);
            foreach (var item in str)
            {
                if (item.Key == "CustomerID")
                {
                    hash.Add("CustomerID", item.Value); 
                } 
                else if (item.Key == "InventoryIDs")
                {
                    string[] str2 = item.Value.ToString().TrimEnd(',').Split(',');
                    hash.Add("GoodsIDs", str2);
                }
            }
            try
            {
                bool b = YZ.GetDatabase(tttagKey).Delete("LendOrder.DelLendOrderByIds", hash) > 0;
                if (b)
                {
                    Msg msgS = new Msg();
                    msgS.TagKey = tttagKey;
                    msgS.Desc = "删除借货单成功" + JsonConvert.SerializeObject(hash);
                    ConmonMQMsgClass.send(msgS);

                    #region 更新商品状态为在库
                    TransmissionOrderResult tor = new TransmissionOrderResult();
                    int totalSeconds;
                    string signStr;
                    string[] str2 =(string[])hash["GoodsIDs"];
                    string batchUpdateDiaParam = "{\"Status\":\"1\",\"filter\":{\"ID\":[";
                    for (int i = 0; i < str2.Length; i++)
                    {
                        if (string.IsNullOrEmpty(str2[i])) continue;
                        if (i == 0)
                            batchUpdateDiaParam += "\"" + str2[i] + "\"";
                        if (i > 0)
                            batchUpdateDiaParam += ",\"" + str2[i] + "\"";
                    }
                    batchUpdateDiaParam += "]}}";
                    var guid = Guid.NewGuid().ToString();
                    var objParams = JsonConvert.DeserializeObject<JObject>(batchUpdateDiaParam);//ID数组使用DeserializeObject.ID单个见加入购物车方法

                    var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);//用NestedDictSort2Str 不用DictSortAnd2Str 11-22
                    MyHttpRequest.SignByParams(guid, lastStr.ToString(), tttagKey, out totalSeconds, out signStr);
                    //获取数据仓库库存（远程） 多个ID获取多条库存
                    var result =
                         MyHttpRequest.PostJSONByRequestParam(
                            new RequestInfo() { RequestJson = batchUpdateDiaParam, RequestUrl = GlobalConfig.TransmissionBatchUpStockURL }
                             , 3, guid, signStr, totalSeconds, null, Yunzuan.Foundation.Web_api.MyHttpRequest.RequestLib.PUT
                    );
                    if (result.Contains(".py"))
                    {
                        result = string.Format(msgInfo, "false", "数据远程服务错误");
                    }
                    msgS = new Msg();
                    msgS.TagKey = tttagKey;
                    msgS.Desc = "批量修改裸钻在库状态：数据中心返回结果" + result;
                    ConmonMQMsgClass.send(msgS);
                    #endregion 


                    return string.Format(CommonConst._msgInfo, "true", "删除借货单成功", 0, 0);
                }
                else
                    return string.Format(CommonConst._msgInfo, "false", "删除借货单失败", 0, 0);
            }
            catch (Exception ex)
            {
                CommonLog.GetMethodInfoAndWriteLogs(type, ex);
                Msg msgS = new Msg();
                msgS.TagKey = tttagKey;
                msgS.Desc = "异常信息：删除借货单" + ex.StackTrace + "参数：" + CommonConst.logParam;
                ConmonMQMsgClass.send(msgS);
                return string.Format(CommonConst._msgInfo, "false", "程序错误", 0, 0);
            }
        }
         
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="goodType"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string UpdateLendOrder(int goodType, string tttagKey, string CustomerID, int[] InventoryIDs)
        {
            for (int i = 0; i < InventoryIDs.Length; i++)
            {
                if (InventoryIDs[i].ToString().Trim() == "") continue;
                Hashtable hash = new Hashtable();
                hash.Add("CustomerID", CustomerID);
                hash.Add("GoodsTypeID", goodType);
                hash.Add("GoodsID", InventoryIDs[i]);
                LendOrder lendorder = YZ.GetDatabase(tttagKey).QueryForObject<LendOrder>("LendOrder.GetLendOrder", hash);
                if (lendorder != null)
                {
                    lendorder.OrderStatus = 1;
                    int result=YZ.GetDatabase(tttagKey).Edit(lendorder);
                    if (result > 0)
                    {
                        Msg msgS = new Msg();
                        msgS.TagKey = tttagKey;
                        msgS.Desc = "更新借货单成功" + JsonConvert.SerializeObject(lendorder);
                        ConmonMQMsgClass.send(msgS);
                        return "1";
                    }
                }
            }
            return "0";
        }
        /// <summary>
        /// 更新借货单
        /// </summary>
        /// <param name="goodType"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string UpdateLendOrderByNo(int goodType, string param)
        {
            HashParam hsParam = JsonConvert.DeserializeObject<HashParam>(param);
            string tttagKey = CommonUrl.getURL(hsParam, param, "更新借货单");
            CommonConst.logParam = param;


            int result = YZ.GetDatabase(tttagKey).Update("LendOrder.updateLendOrderByNo", hsParam);
            if (result > 0)
            {
                Msg msgS = new Msg();
                msgS.TagKey = tttagKey;
                msgS.Desc = "更新借货单成功" + param;
                ConmonMQMsgClass.send(msgS);
                return string.Format(CommonConst._msgInfo, "true", "更新借货单成功",0,0);
            }
            return string.Format(CommonConst.msgObj, "true", "更新借货单成功", 0, 0);
        }
        /// <summary>
        /// 更新借货单
        /// </summary>
        /// <param name="goodType"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string GetLendOrderByNo(int goodType, string param)
        {
            HashParam hsParam = JsonConvert.DeserializeObject<HashParam>(param);
            string tttagKey =  CommonUrl.getURL(hsParam,param);
            CommonConst.logParam = param;

            LendOrder lendOrder = YZ.GetDatabase(tttagKey).QueryForObject<LendOrder>("LendOrder.GetLendOrderByNo", hsParam);//发货单 
            if (lendOrder !=null)
            {
                return string.Format(CommonConst.msgObj, "true", JsonConvert.SerializeObject(lendOrder));//返回Jason数据
            }
            return string.Format(CommonConst.msgObj, "true", "");
        }
        /// <summary>
        /// 获取借货单明细
        /// </summary>
        /// <param name="goodType"></param>
        /// <param name="LendOrderNo"></param>
        /// <returns></returns>
        public static string SearchLendOrderByLendOrderNO(int goodType, string param)
        {
            CommonConst.logParam = param;
            string tttagKey = string.Empty;
            try
            {
                //本地购物车id
                HashParam hash = JsonConvert.DeserializeObject<HashParam>(param);
                tttagKey = CommonUrl.getURL(hash,param, "获取借货单明细");

                hash.Add("GoodsTypeID", goodType);

                IList<LendOrderInfo> cartInfoList = YZ.GetDatabase(tttagKey).QueryForList<LendOrderInfo>("LendOrder.SearchLendOrderByLendOrderNO", hash);//发货单
                if (cartInfoList != null && cartInfoList.Count > 0)
                {
                    Msg msgS = new Msg();
                    msgS.TagKey = tttagKey;
                    msgS.Desc = "获取借货单明细参数：" + CommonClass.GetGemIdsParamByLendOrderList(cartInfoList)+"     URL"+ GoodsType.GetGoodsUrlByTypId(GlobalConfig.filters, goodType);
                    ConmonMQMsgClass.send(msgS);
                    string responseJson = CommonClass.AllProduct(CommonClass.GetGemIdsParamByLendOrderList(cartInfoList), GoodsType.GetGoodsUrlByTypId(GlobalConfig.filters, goodType), tttagKey, "post", true);//得到仓库的数据
                  
                    msgS.TagKey = tttagKey;
                    msgS.Desc = "获取借货单明细返回值：" + responseJson;
                    ConmonMQMsgClass.send(msgS);
                    #region 裸钻
                    if (GoodsType.Diamond == goodType)
                    {
                        string _msgInfo = "{\"msgcode\":#code,\"msginfo\":#msg,\"succ\":#succ,\"fail\":#fail,\"totalrmbct\":#rmbct,\"totalrmb\":#rmb,\"totalusdct\":#usdct,\"totalusd\":#usd}";
                         
                        responseJson = MyHttpRequest.ConvertToInventoryFormat(responseJson);
                        PageList<InventoryInfoResult> _doubleSellInventoryInfos = JsonConvert.DeserializeObject<PageList<InventoryInfoResult>>(responseJson);
                        if (_doubleSellInventoryInfos != null && _doubleSellInventoryInfos.Data.Count > 0)
                        {
                            //拿到商品属性
                            foreach (var item in _doubleSellInventoryInfos.Data)
                            {
                                LendOrderInfo cartInfoList1 = cartInfoList.Where(p => p.GoodsID.Value == item.ID).First();
                                cartInfoList1.Shape = item.Shape;
                                cartInfoList1.Weight = item.Weight;
                                cartInfoList1.Color = item.Color; 
                                cartInfoList1.Clarity = item.Clarity;
                                cartInfoList1.Cut = item.Cut;
                                cartInfoList1.Polish = item.Polish;
                                cartInfoList1.Symmetry = item.Symmetry;
                                cartInfoList1.Fluorescence = item.Fluorescence;
                                cartInfoList1.CertType = item.CertType;
                                cartInfoList1.CertNo = item.CertNo;
                                cartInfoList1.OriginSN = item.OriginSN;
                                cartInfoList1.SN = item.SN;
                                cartInfoList1.Supplier = item.Supplier;
                                cartInfoList1.Status = item.Status;
                                cartInfoList1.Remarks = item.Remark;
                                cartInfoList1.Rapnet = item.Rapnet;
                                cartInfoList1.SourceDiscountReturn = item.SourceDiscountReturn;
                                cartInfoList1.SourceDolarPerGrain = item.SourceDolarPerGrain;
                                cartInfoList1.SourceDolarPerCarat = item.SourceDolarPerCarat;
                            }
                            //删除已被抢购的
                            {
                                string GoodsIDs = "";
                                foreach (LendOrderInfo lendOrder in cartInfoList)
                                {
                                    if (string.IsNullOrEmpty(lendOrder.CertNo))
                                    {
                                        GoodsIDs += lendOrder.GoodsID.Value+",";
                                    }
                                }
                                GoodsIDs=GoodsIDs.TrimEnd(',');
                                if (GoodsIDs.Trim().Length > 0)
                                {
                                    hash.Add("GoodsIDs", GoodsIDs.Split(',').ToArray());
                                    YZ.GetDatabase(tttagKey).Delete("LendOrder.DelLendOrderByIds", hash);
                                }
                            }
                        }
                        else
                        {
                            //全部被抢购
                            //一旦全被抢购，清空本地购物车 11-16
                            #region
                            //清空借货单为XXX的
                            YZ.GetDatabase(tttagKey).Delete("LendOrder.DelLendOrderByIds", hash);
                            #endregion
                            return _msgInfo.Replace("#code", "false").Replace("#msg", JsonConvert.SerializeObject("借货单中现货被抢购一空")).Replace("#succ", JsonConvert.SerializeObject(0)).Replace("#fail", JsonConvert.SerializeObject(cartInfoList.Count)).Replace("#rmbct", JsonConvert.SerializeObject(cartInfoList.Count)).Replace("#rmb", JsonConvert.SerializeObject(0)).Replace("#usdct", JsonConvert.SerializeObject(cartInfoList.Count)).Replace("#usd", JsonConvert.SerializeObject(0));
                        } 
                        return string.Format(CommonConst.msgObj, "true", JsonConvert.SerializeObject(cartInfoList));//返回Jason数据

                    }
                    #endregion
                    else
                    { 
                        HashParam hsParam = JsonConvert.DeserializeObject<HashParam>(responseJson);
                        hsParam.Add("LendOrderNo", cartInfoList[0].LendOrderNo);
                        if (hsParam.Count > 0)
                        {
                            string data = hsParam["rows"].ToString();
                            List<Dictionary<object, object>> listStr = JsonConvert.DeserializeObject<List<Dictionary<object, object>>>(data);
                            CommonClass cc = new CommonClass();
                            for (int i = 0; i < listStr.Count; i++)
                            {
                                if (GoodsType.PrimeGolds == goodType)
                                {
                                    decimal price = Convert.ToDecimal(listStr[i]["TotalWeight"].ToString()) * (Convert.ToDecimal(listStr[i]["GoldPrice"].ToString()) + Convert.ToDecimal(listStr[i]["LaborFee"].ToString()));
                                    listStr[i].Add("Price", price);
                                }
                                else if (GoodsType.InlaySettings == goodType)
                                {
                                    decimal price=(Convert.ToDecimal(listStr[i]["GoldPrice"].ToString()) * Convert.ToDecimal(listStr[i]["NetGoldWeight"].ToString()) * (1 + Convert.ToDecimal(listStr[i]["Wastage"].ToString()))) 
                                        + Convert.ToDecimal(listStr[i]["SideLaborFee"].ToString()) * Convert.ToDecimal(listStr[i]["SideNum"].ToString())
                                        + Convert.ToDecimal(listStr[i]["SidePrice"].ToString())
                                        + Convert.ToDecimal(listStr[i]["LaborFee"].ToString())
                                        + Convert.ToDecimal(listStr[i]["Insurance"].ToString());
                                    listStr[i].Add("Price", price);
                                }
                                
                            }
                            hsParam["rows"] = listStr;
                            responseJson = JsonConvert.SerializeObject(hsParam);
                        }
                        //decimal iscount = CommonClass.GetDiscount(goodType, int.Parse(hash["CustomerID"].ToString()), "0");

                    }
                    return string.Format(CommonConst.msgObj, "true", responseJson);
                }
                else
                {
                    return string.Format(CommonConst._msgInfo, "false", "借货单为空");
                }
            }
            catch (Exception ex)
            {
                CommonLog.GetMethodInfoAndWriteLogs(type, ex);
                Msg msgS = new Msg();
                msgS.TagKey = tttagKey;
                msgS.Desc = "异常信息：查看借货单现货的商品" + ex.StackTrace;
                ConmonMQMsgClass.send(msgS);
                return string.Format(CommonConst._msgInfo, "false", "程序错误");
            } 
        }
        private static void SendMsg(string tel, string salesName, string customerName)
        { 
            //sms
            HashParam hsParam2 = new HashParam();
            hsParam2["salesname"] = getSmsName(salesName);
            hsParam2["cutomername"] = getSmsName(customerName);
            SMSManager.SendSms(tel, SMSLib.SMSLendOrders, hsParam2); //客户
            //sms end
        }
        public static string getSmsName(string name)
        {
            return name.Substring(0, name.Length >= 20 ? 20 : name.Length);
        } 
    }
}